<template>
  <el-row
    :gutter="20"
    :style="{ height: '95vh', padding: '20px', boxSizing: 'border-box' }"
    :class="{ 'is-vertical': isVertical }"
  >
    <!-- 左侧上传区域 -->
    <el-col :span="isVertical ? 24 : 12" class="upload-panel" :style="isVertical ? { marginBottom: '20px' } : {}">
      <el-input v-model="host" placeholder="请输入 host" clearable style="margin-bottom: 20px;" />

      <el-upload
        action=""
        drag
        ref="uploadRef"
        accept=".txt"
        :show-file-list="true"
        :auto-upload="false"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :on-change="handleFileChange"
        class="upload-box"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">拖拽或点击选择 input.txt</div>
      </el-upload>

      <el-button
        type="primary"
        style="margin-top: 20px; width: 100%;"
        :disabled="fileList.length === 0"
        @click="handleUpload"
      >
        上传
      </el-button>
    </el-col>

    <!-- 右侧显示区域 -->
    <el-col :span="isVertical ? 24 : 12" class="display-panel">
      <h3>文本内容</h3>
      <pre class="txt-display">{{ txtContent }}</pre>
    </el-col>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      host: '',
      txtContent: '',
      isVertical: false,
      fileList: []
    }
  },
  mounted() {
    this.checkScreen()
    window.addEventListener('resize', this.checkScreen)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkScreen)
  },
  methods: {
    checkScreen() {
      this.isVertical = window.innerWidth < 768
    },
    beforeUpload(file) {
      // 只保留当前这个文件，替换旧的 fileList
      this.fileList = [{
        name: file.name,
        size: file.size,
        raw: file
      }]

      // 读取文件内容，更新显示和提取 host
      const reader = new FileReader()
      reader.onload = e => {
        const content = e.target.result
        this.txtContent = content
        const match = content.match(/https:\/\/([^\/\s]+)\/public\/other\/statements\/privacy/)
        if (match && match[1]) {
          this.host = match[1]
        }
      }
      reader.readAsText(file)

      return false // 阻止自动上传
    },

    handleFileChange(uploadFile, uploadFiles) {
      // 只保留最新选的文件，替换fileList
      if (uploadFiles.length > 0) {
        const latestFile = uploadFiles[uploadFiles.length - 1]
        this.fileList = [latestFile]

        // 读取内容
        if (latestFile.raw) {
          const reader = new FileReader()
          reader.onload = e => {
            const content = e.target.result
            this.txtContent = content

            const match = content.match(/https:\/\/([^\/\s]+)\/public\//)
            if (match && match[1]) {
              this.host = match[1]
            } else {
              this.host = ''
            }
          }
          reader.readAsText(latestFile.raw)
        }
      } else {
        this.fileList = []
        this.txtContent = ''
        this.host = ''
      }
    },

    async handleUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning('请先选择文件')
        return
      }

      const file = this.fileList[0].raw

      const formData = new FormData()
      formData.append('file', file)
      formData.append('host', this.host)

      console.log('测试上传')
      // try {
      //     // 假设你的上传接口是 /api/upload，使用 fetch 或 axios 发送请求
      //     const res = await fetch('/api/upload', {
      //         method: 'POST',
      //         body: formData
      //     });

      //     if (!res.ok) {
      //         throw new Error('上传失败');
      //     }

      //     this.$message.success('上传成功');
      //     // 上传成功后可清空文件和内容（如果需要）
      //     // this.fileList = [];
      //     // this.txtContent = '';
      // } catch (err) {
      //     this.$message.error(err.message || '上传错误');
      // }
    }
  }
}
</script>

<style>
.upload-box {
    height: 200px;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    background: #fafafa;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    font-size: 16px;
    color: #909399;
    flex-direction: column;
}

.el-upload-dragger {
    width: 200px;
}

.display-panel {
    background: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    padding: 15px;
    overflow: auto;
    height: 80vh;
}

.txt-display {
    white-space: pre-wrap;
    font-family: monospace;
    overflow-y: auto;
}

.el-row.is-vertical {
    flex-direction: column;
}
</style>
